const Service = require('egg').Service

class chronicleService extends Service {
  get Chronicle() {
    return this.ctx.model.Chronicle
  }
  
  // 新增
  async insert(data) {
    const _data = await new this.Chronicle(data)
    _data.save()
    return _data
  }

  // 查询
  async getList(body) {
    const pageNum = Number.parseInt(body.pageNum || 1)
    const pageSize = Number.parseInt(body.pageSize || 10)
    const contentReg = new RegExp(body.content,'ig')
    let params = {}
    if(body.content) {
      params.content = contentReg
    }
    if(body.type) {
      params.type = body.type
    }
    const ret = await this.Chronicle.find(params).skip((pageNum-1)*pageSize).limit(pageSize).populate('img','link')
    const total = await this.Chronicle.countDocuments(params)
    return {
      list: ret,
      total
    }
  }

  // 删除
  async delete(id) {
    const { ctx,service } = this
    const _data = await this.Chronicle.findById(id).populate('img','link')
    if(!_data) {
      ctx.throw('_id不正确！')
    }
    _data.remove()
    
     //删除文件
    if(_data.img) {
      await ctx.model.File.deleteOne({_id:_data.img._id})
      service.toolService.deleteDiskFile(_data.img.link)
    }
    
    return {
      code: 200,
      message: '删除成功'
    }
  }

  // 修改
  async update(body) {
    const { ctx } = this
    const _data = await this.Chronicle.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    return {
      code: 200,
      message: '修改成功'
    }
  }
  
}

module.exports = chronicleService